<template>
	<view class="profile-container">
		<!-- 顶部导航栏 -->
		<view class="header-nav">
			<view class="nav-left" @click="goBack">
				<text class="nav-text">返回</text>
			</view>
			<view class="nav-center">
				<view class="title">修改资料</view>
				<view class="title-line"></view>
			</view>
			<view class="nav-right">
				<!-- 移除保存按钮 -->
			</view>
		</view>
		
		<!-- 主要内容区域 -->
		<view class="form-container">
			<!-- 头像 -->
			<view class="form-item avatar-item">
				<text class="form-label">头像</text>
				<view class="avatar-wrapper" @click="chooseAvatar">
					<image class="avatar" :src="profileForm.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
					<view class="avatar-edit-icon">
						<text class="icon-text">更换</text>
					</view>
				</view>
			</view>
			
			<!-- 昵称 -->
			<view class="form-item">
				<text class="form-label">昵称</text>
				<input class="form-input" type="text" v-model="profileForm.nickName" placeholder="请输入昵称" />
			</view>
			
			<!-- 手机号 -->
			<view class="form-item">
				<text class="form-label">手机号</text>
				<input class="form-input" type="number" v-model="profileForm.phonenumber" placeholder="请输入手机号" maxlength="11" />
			</view>
			
			<!-- 微信号 -->
			<view class="form-item">
				<text class="form-label">微信号</text>
				<input class="form-input" type="text" v-model="profileForm.wechatAccount" placeholder="请输入微信号" />
			</view>
			
			<!-- 邮箱 -->
			<view class="form-item">
				<text class="form-label">邮箱</text>
				<input class="form-input" type="text" v-model="profileForm.email" placeholder="请输入邮箱" />
			</view>
			
			<!-- 性别 -->
			<view class="form-item">
				<text class="form-label">性别</text>
				<view class="form-radio-group">
					<view class="radio-item" :class="{ active: profileForm.sex === '0' }" @click="profileForm.sex = '0'">
						<view class="radio-dot"></view>
						<text class="radio-text">男</text>
					</view>
					<view class="radio-item" :class="{ active: profileForm.sex === '1' }" @click="profileForm.sex = '1'">
						<view class="radio-dot"></view>
						<text class="radio-text">女</text>
					</view>
					<view class="radio-item" :class="{ active: profileForm.sex === '2' }" @click="profileForm.sex = '2'">
						<view class="radio-dot"></view>
						<text class="radio-text">保密</text>
					</view>
				</view>
			</view>
			
			<!-- 保存按钮 -->
			<view class="save-button-wrap">
				<button class="save-button" @click="saveProfile">保存</button>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '../../../api/api.js';
	import { handleAuthError } from '../../../utils/auth.js';
	
	export default {
		data() {
			return {
				userId: '',
				profileForm: {
					userId: '',
					nickName: '',
					phonenumber: '',
					wechatAccount: '',
					sex: '0',
					avatar: '',
					email: ''
				},
				originalProfile: {}
			}
		},
		onLoad() {
			this.getUserInfo();
		},
		methods: {
			async getUserInfo() {
				try {
					// 优先通过API直接获取当前用户信息
					const profileRes = await api.user.getCurrentUserInfo();
					if (profileRes.code === 200 && profileRes.data) {
						this.profileForm = {
							userId: profileRes.data.userId,
							nickName: profileRes.data.nickName || '',
							phonenumber: profileRes.data.phonenumber || '',
							wechatAccount: profileRes.data.wechatAccount || '',
							sex: profileRes.data.sex || '0',
							avatar: profileRes.data.avatar || '',
							email: profileRes.data.email || ''
						};
						
						// 保存到本地存储，确保数据一致性
						const userInfoForStorage = {
							userId: profileRes.data.userId,
							nickName: profileRes.data.nickName,
							avatar: profileRes.data.avatar,
							publisherId: profileRes.data.publisherId
						};
						uni.setStorageSync('userInfo', JSON.stringify(userInfoForStorage));
						
						// 保存原始数据，用于比较是否有修改
						this.originalProfile = JSON.parse(JSON.stringify(this.profileForm));
						return;
					}
					
					// 如果API获取失败，尝试从本地存储获取
					const userInfo = uni.getStorageSync('userInfo');
					if (userInfo) {
						const parsedUserInfo = JSON.parse(userInfo);
						this.userId = parsedUserInfo.userId;
						
						// 获取用户详细信息
						const res = await api.user.userInfo(this.userId);
						if (res.code === 200) {
							this.profileForm = {
								userId: res.data.userId,
								nickName: res.data.nickName || '',
								phonenumber: res.data.phonenumber || '',
								wechatAccount: res.data.wechatAccount || '',
								sex: res.data.sex || '0',
								avatar: res.data.avatar || '',
								email: res.data.email || ''
							};
							// 保存原始数据，用于比较是否有修改
							this.originalProfile = JSON.parse(JSON.stringify(this.profileForm));
						}
					} else {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (err) {
					try {
						await handleAuthError(err);
						this.getUserInfo();
					} catch (error) {
						console.error('获取用户信息失败', error);
						uni.showToast({
							title: '获取用户信息失败',
							icon: 'none'
						});
					}
				}
			},
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 上传头像
						this.uploadAvatar(res.tempFilePaths[0]);
					}
				});
			},
			async uploadAvatar(filePath) {
				uni.showLoading({
					title: '上传中...'
				});
				try {
					// 调用上传API
					const uploadRes = await api.common.uploadFile(filePath);
					if (uploadRes.code === 200) {
						// 更新头像地址为服务器返回的地址
						this.profileForm.avatar = uploadRes.url || uploadRes.data?.url || uploadRes.data;
						uni.hideLoading();
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} else {
						throw new Error(uploadRes.msg || '上传失败');
					}
				} catch (err) {
					uni.hideLoading();
					console.error('上传头像失败', err);
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none'
					});
				}
			},
			async saveProfile() {
				// 表单验证
				if (!this.profileForm.nickName) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none'
					});
					return;
				}
				
				if (this.profileForm.phonenumber && !/^1\d{10}$/.test(this.profileForm.phonenumber)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				// 邮箱格式验证
				if (this.profileForm.email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.profileForm.email)) {
					uni.showToast({
						title: '请输入正确的邮箱',
						icon: 'none'
					});
					return;
				}
				
				// 构建提交数据 - 按照新接口要求的格式
				const submitData = {
					nickName: this.profileForm.nickName,
					phonenumber: this.profileForm.phonenumber || '',
					wechatAccount: this.profileForm.wechatAccount || '',
					sex: this.profileForm.sex || '0'
				};
				
				// 可选参数处理
				if (this.profileForm.email) {
					submitData.email = this.profileForm.email;
				}
				
				// avatar不再通过这个接口提交，应该单独上传
				
				// 显示加载中
				uni.showLoading({
					title: '保存中...'
				});
				
				try {
					// 调用API保存修改
					const res = await api.user.updateUserInfo(submitData);
					uni.hideLoading();
					
					if (res.code === 200) {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						
						// 更新本地存储
						const userInfo = uni.getStorageSync('userInfo');
						if (userInfo) {
							const parsedUserInfo = JSON.parse(userInfo);
							parsedUserInfo.nickName = this.profileForm.nickName;
							// avatar可能已经通过上传接口更新，这里不需要再更新
							uni.setStorageSync('userInfo', JSON.stringify(parsedUserInfo));
						}
						
						// 保存成功后更新原始数据，避免返回时再次提示
						this.originalProfile = JSON.parse(JSON.stringify(this.profileForm));
						
						// 延迟返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg || '保存失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.hideLoading();
					try {
						await handleAuthError(err);
						// 重试保存
						this.saveProfile();
					} catch (error) {
						console.error('保存失败', error);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				}
			},
			goBack() {
				// 检查是否有未保存的修改
				if (JSON.stringify(this.profileForm) !== JSON.stringify(this.originalProfile)) {
					uni.showModal({
						title: '提示',
						content: '您有未保存的修改，确定要返回吗？',
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack();
							}
						}
					});
				} else {
					uni.navigateBack();
				}
			}
		}
	}
</script>

<style lang="scss">
	.profile-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 50rpx; /* 调整底部内边距 */
		position: relative;
	}

	.header-nav {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		padding: 0 20rpx;
		background: linear-gradient(135deg, #FF0000, #FF4D4D);
	}

	.nav-left,
	.nav-right {
		flex: 1;
		height: 60rpx;
		display: flex;
		align-items: center;
	}

	.nav-left {
		padding-left: 10rpx;
	}
	
	.nav-right {
		padding-right: 10rpx;
		display: flex;
		justify-content: flex-end;
	}

	.nav-text {
		font-size: 28rpx;
		color: #FFFFFF;
		padding: 8rpx 20rpx;
		border-radius: 30rpx;
		background-color: rgba(255, 255, 255, 0.2);
	}

	.nav-center {
		flex: 2;
		text-align: center;
	}

	.title {
		font-size: 38rpx;
		font-weight: bold;
		color: #FFFFFF;
		letter-spacing: 2rpx;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
	}

	.title-line {
		width: 100rpx;
		height: 6rpx;
		background: linear-gradient(to right, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.1));
		margin: 8rpx auto 0;
		border-radius: 3rpx;
	}

	.form-container {
		padding: 30rpx 20rpx;
	}

	.form-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 20rpx rgba(255, 0, 0, 0.1);
	}

	.avatar-item {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.form-label {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
		min-width: 140rpx;
	}

	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		text-align: right;
	}

	.avatar-wrapper {
		margin-top: 20rpx;
		width: 150rpx;
		height: 150rpx;
		position: relative;
		align-self: center;
	}

	.avatar {
		width: 150rpx;
		height: 150rpx;
		border-radius: 75rpx;
		border: 2rpx solid rgba(255, 0, 0, 0.2);
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.avatar-edit-icon {
		position: absolute;
		right: -10rpx;
		bottom: -10rpx;
		width: 60rpx;
		height: 60rpx;
		background: linear-gradient(135deg, #FF0000, #FF4D4D);
		border-radius: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 10rpx rgba(255, 0, 0, 0.3);
	}

	.icon-text {
		font-size: 24rpx;
		color: #FFFFFF;
	}

	.form-radio-group {
		flex: 1;
		display: flex;
		justify-content: flex-end;
	}

	.radio-item {
		display: flex;
		align-items: center;
		margin-left: 30rpx;
	}

	.radio-dot {
		width: 36rpx;
		height: 36rpx;
		border-radius: 18rpx;
		border: 2rpx solid #ddd;
		margin-right: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.radio-item.active .radio-dot {
		border-color: #FF0000;
	}

	.radio-item.active .radio-dot:after {
		content: "";
		width: 20rpx;
		height: 20rpx;
		border-radius: 10rpx;
		background-color: #FF0000;
	}

	.radio-text {
		font-size: 28rpx;
		color: #333;
	}
	
	/* 新增保存按钮样式 */
	.save-button-wrap {
		margin-top: 60rpx;
		padding: 0 20rpx;
	}
	
	.save-button {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		background: linear-gradient(135deg, #FF0000, #FF4D4D);
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		border-radius: 45rpx;
		box-shadow: 0 4rpx 12rpx rgba(255, 0, 0, 0.3);
		transition: all 0.3s;
	}
	
	.save-button:active {
		transform: scale(0.98);
		box-shadow: 0 2rpx 8rpx rgba(255, 0, 0, 0.3);
	}
</style> 